package net.interest.curation.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.interest.curation.meta.FacebookUserMeta;
import net.interest.curation.model.FacebookUser;
import net.interest.curation.model.SocialUser;
import net.interest.curation.model.TwitterUser;

import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class FacebookService implements SocialService {
    private static final Logger log =
        Logger.getLogger(FacebookService.class.getName());
    
    //private static String APP_ID = "174829262593762";
    //private static String APP_ID = "221561241236684";//local
    private static String APP_ID = "284134698286806";
    
    //private static String APP_SECRET = "cce28c79ceb2be154b672b2430034eab";
    //private static String APP_SECRET = "b7d9e217a4df1380ac0e69d2896cf78c";
    private static String APP_SECRET = "a89db22fe0271498d921558b05d10eaf";
    
    public String getAuthorizeUrl(HttpServletRequest req, String callbackUrl)  throws IOException {
       return "https://www.facebook.com/dialog/oauth?client_id="+ APP_ID+ "&redirect_uri=" + URLEncoder.encode(callbackUrl, "UTF-8") + "&scope=offline_access,email,read_stream";
    }

    public SocialUser getAuthorizedUser(String token, String ... args) throws IOException {
        System.out.println(token);
        URL url = new URL("https://graph.facebook.com/oauth/access_token?"+
            "client_id=" + APP_ID + 
            "&redirect_uri="+args[0]+
            "&client_secret=" + APP_SECRET + "&code="+ token);
        String response = new BufferedReader(new InputStreamReader(url.openStream())).readLine();
        System.out.println(response);
        //TODO: なんかMultipartform dataのパーサーないのかな。
        String access_token = response.split("&")[0].split("=")[1];
        
        URL graphUrl = new URL("https://graph.facebook.com/me?access_token=" + access_token);

        String graphResponse = new BufferedReader(new InputStreamReader(graphUrl.openStream())).readLine();
        
        
        String screenName = null;
        try {
            System.out.println(graphResponse);
            JSONObject userJson = new JSONObject( graphResponse );
            screenName = userJson.getString("username");
            System.out.println(userJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        FacebookUserMeta meta = FacebookUserMeta.get();
        FacebookUser user = null;
        if(screenName != null)
            user = Datastore.query(meta).filter(meta.screenName.equal(screenName)).asSingle();
        
        System.out.println("******* user= " + user);
        if(user== null){
            Key key = Datastore.allocateId(FacebookUser.class);
            user = new FacebookUser();
            user.setScreenName(screenName);
            user.setKey(key);
            Datastore.put(user);
        }
        user.setAccessToken(access_token);
        return user;
    }

}
